# -*- coding:UTF-8 -*-
'''
开发环境：PyCharm
创建日期：2025/8/12 10:58
作   者：新启典学苑-樱桃
描   述：对selenium相关的功能进行封装
       1. 适配各种类型的浏览器，写的代码在edge、chrome、firefox等都能执行
       2. 优化定位元素的方式
       3. 定位元素使用显式等待，增加异常处理
'''
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait


def get_driver(browser="edge"):
    if browser == "edge":
        driver = webdriver.Edge()
    elif browser == "chrome":
        driver = webdriver.Chrome()
    elif browser == "firefox":
        driver = webdriver.Firefox()
    # 还有其他类型的浏览器，省略了
    else:
        driver = webdriver.Edge()
    return driver


class BasePage():
    def __init__(self, driver):
        self.driver = driver  # 初始化一个driver，后续页面上的元素都使用这个driver来定位

    # id=kw
    # xpath=/html/body/div
    # name=wd
    # xpath=//*[属性1=值1]
    def locate_element(self, target):
        '''
        定位元素
        :param target: 表示要定位的元素
        :return: WebElement，定位到的元素
        '''
        i = target.index("=")  # 找到第一个等号的位置
        by = target[:i].strip()  # 切片
        value = target[i + 1:].strip()
        locator = by, value  # 构造locator元组
        # locator = ("id", "kw")
        # locator = ("name", "wd")
        # locator = By.ID, "kw"
        try:
            a = WebDriverWait(self.driver, 10, 0.5).until(
                expected_conditions.presence_of_element_located(locator)
            )
            print(f"定位元素{target}成功")
            return a
        except Exception as e:
            print(f"定位元素{target}失败，异常信息为：{e}")

    # 点击目标元素target
    def click(self, target):
        self.locate_element(target).click()

    # 给目标元素target中输入值value
    def send_keys(self, target, value):
        a = self.locate_element(target)
        a.clear()
        a.send_keys(value)

    def open(self, url):
        self.driver.get(url)  # 打开网页
        self.driver.maximize_window()  # 窗口最大化
        self.driver.implicitly_wait(10)  # 隐式等待

    # 退出浏览器
    def quit(self):
        self.driver.quit()

    # 切换iframe
    def switch_iframe(self, target):
        a = self.locate_element(target)
        self.driver.switch_to.frame(a)

    # 回到最外层的iframe
    def switch_default_conent(self):
        self.driver.switch_to.default_content()

    # 根据文本选择下拉框的内容
    def select_by_text(self, target, text):
        a = self.locate_element(target)
        a = Select(a)
        a.select_by_visible_text(text)

    # 根据value选择下拉框的内容
    def select_by_value(self, target, value):
        a = self.locate_element(target)
        a = Select(a)
        a.select_by_value(value)


# 测试代码，用完可以删除，不影响整体的测试框架
if __name__ == '__main__':
    from time import sleep

    driver = get_driver()
    bp = BasePage(driver)
    bp.open("http://www.baidu.com")
    # input()
    # 不太懂代码，懂业务的情况下，也能写出来
    bp.send_keys("id=chat-textarea", "自动化测试框架")
    bp.click("id=chat-submit-button")
    sleep(5)
